package com.ncbee.base.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ncbee.base.config.shiro.annotation.RequiresExtPermissions;
import com.ncbee.base.model.entity.Resource;
import com.ncbee.base.model.vo.BaseQuery;
import com.ncbee.base.model.vo.TreeVo;
import com.ncbee.base.service.ResourceService;
import com.ncbee.base.util.StringUtils;
import com.ncbee.base.web.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author youdianyun
 * @since 2018-11-23
 */
@Controller
@RequestMapping("/resource")
@RequiresExtPermissions("resource:")
public class ResourceController extends BaseController<Resource> {
    private static final Logger logger = LoggerFactory.getLogger(ResourceController.class);
    @Autowired
    private ResourceService resourceService;

    @Override
    protected IService<Resource> getTargetService() {
        return resourceService;
    }


    @Override
    public String getListPageUrl() {
        return "resource/listPage";
    }

    @Override
    protected String getAddPageUrl() {
        return "resource/addPage";
    }

    @Override
    protected String getEditPageUrl() {
        return "resource/editPage";
    }

    @ResponseBody
    @RequestMapping("/list")
    public Object list(HttpServletRequest request, BaseQuery baseQuery){
        IPage<Resource> page=new Page<Resource>();
        if(baseQuery.getPage()!=null){
            page.setCurrent(baseQuery.getPage());
        }if(baseQuery.getLimit()!=null){
            page.setSize(baseQuery.getLimit());
        }
        QueryWrapper<Resource> queryWrapper=new QueryWrapper<Resource>();
        queryWrapper.orderByAsc("pid");
        IPage<Resource> result=resourceService.page(page,queryWrapper);

        return renderPage(result);
    }

    /**
     * 查询所有的树节点
     * @return
     */
    @ResponseBody
    @RequestMapping("showResourceTree")
    public Object showResourceTree(){
       List<TreeVo> treeList=resourceService.findResourceMenuTree();
    return treeList;
    }
    /*
     * 删除当前资源之前，先删除当前资源的子节点
     */
    @Override
    protected void beforeDelete(HttpServletRequest request, String ids) {
        Resource resource=resourceService.getById(ids);
        List<Long> idsList=new ArrayList<Long>();
        QueryWrapper<Resource> queryWrapper=new QueryWrapper<Resource>();
        queryWrapper.likeRight("pre_pid",resource.getPrePid()+",");
        //查询当前资源的子资源
        List<Resource> resourceList=resourceService.list(queryWrapper);
        for(Resource r:resourceList){
            idsList.add(r.getId());
        }
        if(idsList.size()>0){
            resourceService.removeByIds(idsList);
        }
    }

    /**
     * 新增资源之后,维护子父级之间的关系
     */
    @Override
    protected void afterSave(HttpServletRequest request,Resource resource){
        Long id=resource.getId();//获取返回的主键
        Long pid=resource.getPid();//获取父id
        StringBuffer pidS=new StringBuffer();
        //如果没有选择父节点
        if(pid==null){
            pidS.append(id);
        }else{
          //选择了父节点
          Resource parentResource=resourceService.getById(pid);
          String parentPidS=parentResource.getPrePid();//获取父节点的所有上级资源
            pidS.append(parentPidS).append(",").append(id);
        }
        resource.setPrePid(pidS.toString());
        resource.setCreateTime(LocalDateTime.now());
         boolean flag=resourceService.updateById(resource);
         logger.info("---------新增资源成功维护子父级关系结果------："+flag);
    }
    /**
     *  显示更新页面之前
     *  查询当前资源以及当前资源子资源
     */
    @Override
    protected void beforeShowEdit(HttpServletRequest request, Resource resource){
        String prePid=resource.getPrePid();
        QueryWrapper<Resource> queryWrapper=new QueryWrapper<Resource>();
        queryWrapper.likeRight("pre_pid",prePid+",");
        //查询子资源
        List<Resource> resourceList=resourceService.list(queryWrapper);
        if(CollectionUtils.isEmpty(resourceList)){
            resourceList=new ArrayList<>();
        }
        resourceList.add(resource);
        String  resourceListStr=JSONObject.toJSONString(resourceList);
        request.setAttribute("resourceListStr",resourceListStr);
    }
    /**
     * 更新记录之前
     */
    @Override
    protected void beforeUpdate(HttpServletRequest request, Resource resource) {
        Long pid=resource.getPid();
        Resource dbResource=resourceService.getById(resource.getId());
        Long dbPid=dbResource.getPid();
        //无值相等 未改变
        if(pid==dbPid){
            return;
        }
        //有值相等,未改变
        if(pid!=null&&dbPid!=null){
            if(pid.intValue()==dbPid.intValue()){
                return;
            }
        }
        List<Resource> updateList=new ArrayList<Resource>();
        QueryWrapper<Resource> queryWrapper=new QueryWrapper<Resource>();
        //查询当前资源所有的子资源。
        queryWrapper.likeRight("pre_pid",resource.getPrePid()+",");
        List<Resource> childResourceList=resourceService.list(queryWrapper);
        if(pid==null){//当前资源至于顶级节点
            resource.setPrePid(resource.getId()+"");
            for(Resource r:childResourceList){
                String prePid=r.getPrePid();
                String newPrePid= StringUtils.getUpdatePidStr(prePid,resource.getId()+"");
                r.setPrePid(newPrePid);
                updateList.add(r);
            }
        }else{
            Resource parentResource=resourceService.getById(pid);
            String parentPrePid=parentResource.getPrePid();//5,6
            String oldPrePid=resource.getPrePid();//7
            String newPrePid= StringUtils.getUpdatePidStr(oldPrePid,resource.getId()+"");
            resource.setPrePid(parentPrePid+","+newPrePid);
            for(Resource r:childResourceList){
                String prePid=r.getPrePid();
                String childNewPrePid= StringUtils.getUpdatePidStr(prePid,resource.getId()+"");
                r.setPrePid(parentPrePid+","+childNewPrePid);
                updateList.add(r);
            }
        }
        if(!CollectionUtils.isEmpty(updateList)){
            boolean flag=resourceService.updateBatchById(updateList);
            if(flag){
                logger.info("----成功维护了"+(updateList.size()+1)+"对父子关系---");
            }

        }
        //设置更新时间
        resource.setUpdateTime(LocalDateTime.now());
    }
}

